package com.andnnl.utils;

import javax.net.ssl.*;
import java.io.*;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class HttpsUtil {

    private static final class DefaultTrustManager implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    }

    private static HttpsURLConnection getHttpsURLConnection(String uri, String method, int timeout) throws IOException {
        SSLContext ctx = null;
        try {
            ctx = SSLContext.getInstance("TLS");
            ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        SSLSocketFactory ssf = ctx.getSocketFactory();

        URL url = new URL(uri);
        HttpsURLConnection httpsConn = (HttpsURLConnection) url.openConnection();
        httpsConn.setSSLSocketFactory(ssf);
        httpsConn.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        });
        httpsConn.setRequestMethod(method);
        httpsConn.setDoInput(true);
        httpsConn.setDoOutput(true);
        httpsConn.setReadTimeout(timeout);
        httpsConn.setConnectTimeout(timeout);
		return httpsConn;
    }

    private static byte[] getBytesFromStream(InputStream is) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] kb = new byte[1024];
        int len;
        while ((len = is.read(kb)) != -1) {
            baos.write(kb, 0, len);
        }
        byte[] bytes = baos.toByteArray();
        baos.close();
        is.close();
        return bytes;
    }

    private static void setBytesToStream(OutputStream os, byte[] bytes) throws IOException {
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        byte[] kb = new byte[1024];
        int len;
        while ((len = bais.read(kb)) != -1) {
            os.write(kb, 0, len);
        }
        os.flush();
        os.close();
        bais.close();
    }

    public static byte[] doGet(String uri, int timeout) throws IOException {
        HttpsURLConnection httpsConn = getHttpsURLConnection(uri, "GET", timeout);
        return getBytesFromStream(httpsConn.getInputStream());
    }

    public static String doPost(String uri, String data, int timeout) {
        HttpsURLConnection httpsConn;
		try {
			httpsConn = getHttpsURLConnection(uri, "POST", timeout);
			setBytesToStream(httpsConn.getOutputStream(), data.getBytes());
			byte[] bytes = getBytesFromStream(httpsConn.getInputStream());
			if(bytes!=null && bytes.length>0){
				return new String (bytes,"utf-8");
			}
	        return "";
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return e.getMessage();
			
		}
        
    }
    
    
    public static void main(String[] args) {
//    	String uri = "https://183.62.200.106:8630/hug_interview/sms/receive";
    	String uri = "https://csms-statusopen.iboxpay.com/base-sms-status/api/dx/report";
        byte[] bytes;
	
//			bytes = HttpsUtil.doPost(uri,"<returnForm><type>1</type><count>1</count><list><pushStatusForm><eprId>2231</eprId><mobile>18782629121</mobile><msgId>3450747554119680</msgId><status>1</status><statusCode>DELIVRD</statusCode><userId>szhzkjhhr</userId></pushStatusForm></list></returnForm>",3000);
		String rs = HttpsUtil.doPost(uri,"<returnForm><type>1</type><count>1</count><list><pushStatusForm><eprId>2231</eprId><mobile>18768810119</mobile><msgId>3449208196251648</msgId><status>0</status><statusCode>IC:0055</statusCode><userId>szhzkjhhr</userId></pushStatusForm></list></returnForm>",3000);
		System.out.println("rs: "+rs);

        
	}
}